package com.yds.developtools.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager

/**
 * 作者:     YDS
 * 创建时间: 2023/5/29 10:19
 * 页面描述: 电池电量、电压帮助类
 */
@Suppress("unused")
object YDSBatteryHelper : YDSBaseHelper() {
    private var receiver: BatteryBroadcastReceiver? = null
    private var mBatteryStateListener: BatteryStateListener? = null

    init {
        receiver = BatteryBroadcastReceiver()
    }

    /*** 作者: YDS 时间: 2023/5/29 10:06 描述: 注册电池监测广播 ***/
    fun register(listener: BatteryStateListener) {
        mBatteryStateListener = listener
        receiver?.let {
            val filter = IntentFilter().apply {
                addAction(Intent.ACTION_BATTERY_CHANGED)
                addAction(Intent.ACTION_BATTERY_LOW)
                addAction(Intent.ACTION_BATTERY_OKAY)
                addAction(Intent.ACTION_POWER_CONNECTED)
                addAction(Intent.ACTION_POWER_DISCONNECTED)
            }
            getContext().registerReceiver(it, filter)
        }
    }

    /*** 作者: YDS 时间: 2023/5/29 10:06 描述: 取消注册电池监测广播 ***/
    fun unregister() {
        receiver?.let { getContext().unregisterReceiver(it) }
    }

    private class BatteryBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                when (it.action) {
                    Intent.ACTION_BATTERY_CHANGED -> {
                        // 电量
                        val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                        // 电压
                        val voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                        mBatteryStateListener?.onStatePowerChanged(level, voltage)
                    }
                    Intent.ACTION_BATTERY_LOW -> mBatteryStateListener?.onStatePowerLow()
                    Intent.ACTION_BATTERY_OKAY -> mBatteryStateListener?.onStatePowerOkay()
                    Intent.ACTION_POWER_CONNECTED -> mBatteryStateListener?.onStatePowerConnected()
                    Intent.ACTION_POWER_DISCONNECTED -> mBatteryStateListener?.onStatePowerDisconnected()
                    else -> {
                        mBatteryStateListener?.onStateOthers()
                    }
                }
            }
        }
    }

    interface BatteryStateListener {
        fun onStatePowerChanged(level: Int, voltage: Int)
        fun onStatePowerLow()
        fun onStatePowerOkay()
        fun onStatePowerConnected()
        fun onStatePowerDisconnected()
        fun onStateOthers()
    }
}